<template>
  <div>
    <div class="address-management">
      <!-- 返回按钮 -->
      <el-button
        style="
          background-color: #409eff;
          color: white;
          font-weight: 700;
          margin: 10px 0 20px 10px;
        "
        @click="goBack"
        class="back-button"
      >
        <el-icon><DArrowLeft /></el-icon>
        {{ $t("userLocation.backButtonText") }}
      </el-button>
      <!-- 页面标题和添加地址按钮 -->
      <div class="header">
        <h2>{{ $t("userLocation.pageTitle") }}</h2>
        <button @click="showAddAddressModal = true" class="add-address-btn">
          <i class="el-icon-plus"></i>
          {{ $t("userLocation.addAddressButtonText") }}
        </button>
      </div>
      <!-- 地址列表 -->
      <table class="address-table">
        <thead>
          <tr>
            <th class="default-address-col">
              {{ $t("userLocation.consigneeLabel") }}
            </th>
            <th>{{ $t("userLocation.phoneLabel") }}</th>
            <th>{{ $t("userLocation.addressLabel") }}</th>
            <th>{{ $t("userLocation.operationLabel") }}</th>
            <th>{{ $t("userLocation.defaultAddressLabel") }}</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(address, index) in addresses"
            :key="index"
            class="address-item"
          >
            <td>{{ address.consignee }}</td>
            <td>{{ address.phone }}</td>
            <td
              :title="`${address.province} ${address.city} ${address.district} ${address.streetAddress}`"
              class="ellipsis-address"
            >
              {{ address.address }}
            </td>
            <td>
              <button
                @click="openEditAddressModal(address)"
                class="action-btn edit-btn"
              >
                <i class="el-icon-edit"></i>{{ $t("selectAll.editButtonText") }}
              </button>
              <button
                @click="deleteAddress(index)"
                class="action-btn delete-btn"
              >
                <i class="el-icon-delete"></i>
                {{ $t("selectAll.deleteButtonText") }}
              </button>
            </td>
            <td class="default-address-col">
              <span v-if="address.isDefault" class="default-tag">{{
                $t("userLocation.defaultTagText")
              }}</span>
              <span
                v-else
                @click="setDefaultAddress(index)"
                class="set-default-btn"
                >{{ $t("userLocation.setDefaultButtonText") }}</span
              >
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 添加地址模态框 -->
      <div v-if="showAddAddressModal" class="modal">
        <div class="modal-content">
          <h3>{{ $t("userLocation.addAddressModalTitle") }}</h3>
          <form @submit.prevent="addAddress">
            <div class="form-group">
              <label for="receiver"
                >{{ $t("userLocation.consigneeLabel") }}:</label
              >
              <input
                v-model="newAddress.consignee"
                type="text"
                required
                id="receiver"
              />
            </div>
            <div class="form-group">
              <label for="phone">{{ $t("userLocation.phoneLabel") }}:</label>
              <input
                v-model="newAddress.phone"
                type="text"
                required
                id="phone"
              />
            </div>
            <div class="form-group">
              <label for="region">{{ $t("userLocation.addressLabel") }}:</label>
              <!--            整合省市区联动选择器-->
              <div class="address-select-group">
                <el-select
                  v-model="newAddress.province"
                  @change="choseProvince"
                  :placeholder="$t('userLocation.provincePlaceholder')"
                >
                  <el-option
                    v-for="(item, $index) in province"
                    :key="$index"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="newAddress.city"
                  @change="choseCity"
                  :placeholder="$t('userLocation.cityPlaceholder')"
                >
                  <el-option
                    v-for="(item, $index) in city"
                    :key="$index"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="newAddress.district"
                  @change="choseDistrict"
                  :placeholder="$t('userLocation.districtPlaceholder')"
                >
                  <el-option
                    v-for="(item, $index) in district"
                    :key="$index"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
              <input
                v-model="newAddress.streetAddress"
                type="text"
                required
                id="region"
                :placeholder="$t('userLocation.streetAddressPlaceholder')"
              />
            </div>
            <div class="form-buttons">
              <button type="submit" class="submit-btn">
                {{ $t("userLocation.saveButtonText") }}
              </button>
              <button @click="showAddAddressModal = false" class="cancel-btn">
                {{ $t("userLocation.cancelButtonText") }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- 修改地址模态框 -->
      <div v-if="showEditAddressModal" class="modal">
        <div class="modal-content">
          <h3>{{ $t("userLocation.editAddressModalTitle") }}</h3>
          <form @submit.prevent="updateAddress">
            <div class="form-group">
              <label for="edit-receiver"
                >{{ $t("userLocation.consigneeLabel") }}:</label
              >
              <input
                v-model="editAddress.consignee"
                type="text"
                required
                id="edit-receiver"
              />
            </div>
            <div class="form-group">
              <label for="edit-phone"
                >{{ $t("userLocation.phoneLabel") }}:</label
              >
              <input
                v-model="editAddress.phone"
                type="text"
                required
                id="edit-phone"
              />
            </div>
            <div class="form-group">
              <label for="edit-region"
                >{{ $t("userLocation.addressLabel") }}:</label
              >
              <!--            整合省市区联动选择器-->
              <div class="address-select-group">
                <el-select
                  v-model="editAddress.province"
                  @change="choseProvinceEdit"
                  :placeholder="$t('userLocation.provincePlaceholder')"
                >
                  <el-option
                    v-for="(item, $index) in province"
                    :key="$index"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="editAddress.city"
                  @change="choseCityEdit"
                  :placeholder="$t('userLocation.cityPlaceholder')"
                >
                  <el-option
                    v-for="(item, $index) in cityEdit"
                    :key="$index"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="editAddress.district"
                  @change="choseDistrictEdit"
                  :placeholder="$t('userLocation.districtPlaceholder')"
                >
                  <el-option
                    v-for="(item, $index) in districtEdit"
                    :key="$index"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
              <input
                v-model="editAddress.address"
                type="text"
                required
                id="edit-region"
                :placeholder="$t('userLocation.streetAddressPlaceholder')"
              />
            </div>
            <div class="form-buttons">
              <button type="submit" class="submit-btn">
                {{ $t("userLocation.saveButtonText") }}
              </button>
              <button @click="showEditAddressModal = false" class="cancel-btn">
                {{ $t("userLocation.cancelButtonText") }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import "../../assets/css/UserLocation.css";
import { onMounted, ref } from "vue";
import ChineseDistricts from "../../utils/area.js";
import router from "@/router/index.js";
import { DArrowLeft } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";

const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerid = userInfo.id;
const route = useRoute();

// 添加地址相关
const showAddAddressModal = ref(false);
const newAddress = ref({
  userId: "",
  consignee: "",
  phone: "",
  province: "",
  city: "",
  district: "",
  streetAddress: "",
});

// 修改地址相关
const showEditAddressModal = ref(false);
const editAddress = ref({});
// 存储地址数据
const addresses = ref([]);

// 省市区数据
const province = ref([]);
const city = ref([]);
const district = ref([]);
const cityEdit = ref([]);
const districtEdit = ref([]);

// 加载省市区数据
const loadAreaData = () => {
  ChineseDistricts.forEach((item) => {
    province.value.push({
      id: item.code,
      value: item.name,
      children: item.cityList,
    });
  });
};

// 添加地址方法
const addAddress = () => {
  // 检查新地址信息是否完整
  if (
    !newAddress.value.consignee ||
    !newAddress.value.phone ||
    !newAddress.value.province ||
    !newAddress.value.city ||
    !newAddress.value.district ||
    !newAddress.value.streetAddress
  ) {
    ElMessage({
      message: "地址信息不完整，请填写完整",
      type: "error",
    });
    return;
  }
  // 验证电话号码长度
  if (newAddress.value.phone.length > 11) {
    ElMessage({
      message: "电话号码不能超过十一位",
      type: "error",
    });
    return;
  }
  //将用户ID赋值给newAddress，使用解构赋值确保响应式更新
  newAddress.value = {
    ...newAddress.value,
    userId: buyerid,
  };
  console.log("newAddress:", newAddress.value);

  // 将代码转换为具体地址名称
  const provinceItem = province.value.find(
    (item) => item.id === newAddress.value.province
  );
  const cityItem = city.value.find((item) => item.id === newAddress.value.city);
  const districtItem = district.value.find(
    (item) => item.id === newAddress.value.district
  );

  newAddress.value.province = provinceItem ? provinceItem.value : "";
  newAddress.value.city = cityItem ? cityItem.value : "";
  newAddress.value.district = districtItem ? districtItem.value : "";
  newAddress.value.address = `${newAddress.value.province} ${newAddress.value.city} ${newAddress.value.district} ${newAddress.value.streetAddress}`;

  console.log("newAddress:", newAddress.value);

  // 调用后端接口添加地址
  request
    .post("/address/add", newAddress.value)
    .then((res) => {
      if (res.msg === "成功") {
        const newAddressWithId = {
          ...newAddress.value,
          id: Date.now(),
          isDefault: false,
        };

        // 成功后在本地更新地址列表
        addresses.value.push(newAddressWithId);
        showAddAddressModal.value = false;
        newAddress.value = {
          userId: "",
          consignee: "",
          phone: "",
          province: "",
          city: "",
          district: "",
          streetAddress: "",
        };
        getAllAddress();
      } else {
        ElMessage({
          message: "新增地址失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("新增地址失败", err);
      ElMessage({
        message: "新增地址失败，请稍后重试",
        type: "error",
      });
    });
};

// 修改地址方法
const updateAddress = () => {
  // 检查 editAddress 是否有值
  if (!editAddress.value || Object.keys(editAddress.value).length === 0) {
    ElMessage({
      message: "没有要修改的地址信息",
      type: "error",
    });
    return;
  }
  // 验证电话号码长度
  if (editAddress.value.phone.length > 11) {
    ElMessage({
      message: "电话号码不能超过十一位",
      type: "error",
    });
  } else {
    // 将 id 转换为对应的名称
    const provinceItem = province.value.find(
      (item) => item.id === editAddress.value.province
    );
    const cityItem = cityEdit.value.find(
      (item) => item.id === editAddress.value.city
    );
    const districtItem = districtEdit.value.find(
      (item) => item.id === editAddress.value.district
    );

    editAddress.value.province = provinceItem ? provinceItem.value : "";
    editAddress.value.city = cityItem ? cityItem.value : "";
    editAddress.value.district = districtItem ? districtItem.value : "";

    // 调用后端接口修改地址
    request
      .put("/address/update", editAddress.value)
      .then((res) => {
        if (res.msg === "成功") {
          const index = addresses.value.findIndex(
            (addr) => addr.id === editAddress.value.id
          );
          if (index !== -1) {
            addresses.value[index] = {
              ...editAddress.value,
            };
          }
          showEditAddressModal.value = false;
          getAllAddress();
        } else {
          ElMessage({
            message: "修改地址失败",
            type: "error",
          });
        }
      })
      .catch((err) => {
        console.error("修改地址失败", err);
        ElMessage({
          message: "修改地址失败，请稍后重试",
          type: "error",
        });
      });
  }
};

// 删除地址方法
const deleteAddress = (index) => {
  if (index < 0 || index >= addresses.value.length) {
    ElMessage({
      message: "无效的索引",
      type: "error",
    });
    return;
  }
  const addressId = addresses.value[index].id;
  request
    .delete(`/address/delete/${addressId}`)
    .then((res) => {
      if (res.msg === "成功") {
        addresses.value.splice(index, buyerid);
        getAllAddress();
        ElMessage({
          message: "成功删除地址！",
          type: "success",
        });
      } else {
        ElMessage({
          message: "删除地址失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.log("删除地址失败", err);
      ElMessage({
        message: "删除地址失败",
        type: "error",
      });
    });
};

// 设置默认地址方法
const setDefaultAddress = (index) => {
  // 检查索引是否有效
  if (index < 0 || index >= addresses.value.length) {
    ElMessage({
      message: "索引无效",
      type: "error",
    });
    return;
  }

  // 将布尔类型的 isDefault 转换为整数类型
  const selectedAddress = addresses.value[index];
  selectedAddress.isDefault = selectedAddress.isDefault ? 1 : 0;
  // 调用后端接口设置默认地址
  request
    .post("/address/setdefault", selectedAddress)
    .then((res) => {
      if (res.msg === "成功") {
        // 本地更新所有地址的默认状态，将选中的设为默认
        addresses.value.forEach((addr) => (addr.isDefault = false));
        selectedAddress.isDefault = true;
        getAllAddress();
      } else {
        ElMessage({
          message: "设置默认地址失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("设置默认地址失败", err);
      ElMessage({
        message: "设置默认地址失败，请稍后重试",
        type: "error",
      });
    });
};

//获取用户地址
const getAllAddress = () => {
  request
    .get(`address/getAll/${buyerid}`)
    .then((res) => {
      if (res.msg === "成功") {
        addresses.value = res.data.map((addr) => {
          addr.address = `${addr.province} ${addr.city} ${addr.district} ${addr.streetAddress}`;
          return addr;
        });
        // 在数据加载完成后调用确保默认地址在第一个位置的函数
        ensureDefaultAddressFirst();
      } else {
        ElMessage({
          message: "获取地址数据失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("获取地址数据失败", err);
      ElMessage({
        message: "获取地址数据失败，请稍后重试",
        type: "error",
      });
    });
};

// 确保默认地址在第一个位置
const ensureDefaultAddressFirst = () => {
  const defaultAddress = addresses.value.find((addr) => addr.isDefault === 1);
  if (defaultAddress) {
    const index = addresses.value.indexOf(defaultAddress);
    addresses.value.splice(index, 1);
    addresses.value.unshift(defaultAddress);
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 选择省份（添加地址）
const choseProvince = (e) => {
  city.value = [];
  district.value = [];
  newAddress.value.city = "";
  newAddress.value.district = "";
  for (const item of province.value) {
    if (e === item.id) {
      item.children.forEach((citem) => {
        city.value.push({
          id: citem.code,
          value: citem.name,
          children: citem.areaList,
        });
      });
    }
  }
};

// 选择城市（添加地址）
const choseCity = (e) => {
  district.value = [];
  newAddress.value.district = "";
  for (const item of city.value) {
    if (e === item.id) {
      item.children.forEach((bitem) => {
        district.value.push({
          id: bitem.code,
          value: bitem.name,
        });
      });
    }
  }
};

// 选择区域（添加地址）
const choseDistrict = (e) => {
  newAddress.value.district = e;
};

// 初始化修改地址的选择器
const initEditAddressSelects = () => {
  cityEdit.value = [];
  districtEdit.value = [];
  choseProvinceEdit(editAddress.value.province);
  choseCityEdit(editAddress.value.city);
};

// 选择省份（修改地址）
const choseProvinceEdit = (e) => {
  cityEdit.value = [];
  districtEdit.value = [];
  editAddress.value.city = "";
  editAddress.value.district = "";
  for (const item of province.value) {
    if (e === item.id) {
      item.children.forEach((citem) => {
        cityEdit.value.push({
          id: citem.code,
          value: citem.name,
          children: citem.areaList,
        });
      });
    }
  }
};

// 选择城市（修改地址）
const choseCityEdit = (e) => {
  districtEdit.value = [];
  editAddress.value.district = "";
  for (const item of cityEdit.value) {
    if (e === item.id) {
      item.children.forEach((bitem) => {
        districtEdit.value.push({
          id: bitem.code,
          value: bitem.name,
        });
      });
    }
  }
};

// 选择区域（修改地址）
const choseDistrictEdit = (e) => {
  editAddress.value.district = e;
};

// 打开修改地址模态框
const openEditAddressModal = (address) => {
  editAddress.value = { ...address };
  showEditAddressModal.value = true;
  initEditAddressSelects();
};

onMounted(() => {
  const needRefresh = route.query.needRefresh;
  if (needRefresh) {
    getAllAddress();
  }
  loadAreaData();
  getAllAddress(); // 页面加载时获取地址数据
});
</script>
